package com.ComputerSales.controller;


import cn.dev33.satoken.util.SaResult;
import com.ComputerSales.entity.Product;
import com.ComputerSales.service.IProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 作者
 * @since 2024-06-26
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    @GetMapping("/add")
    public String toAdd() {
        return "admin/product_add";
    }

    @PostMapping
    @ResponseBody
    public SaResult addProduct(Product product) {
        if (product.getImgUrl().isEmpty()) {
            product.setImgUrl("http://cdn.qiniu.liyansheng.top/img/20240626155220.png");
        }
        if (product.getId() == null) {
            productService.save(product);
        } else {
            productService.updateById(product);

        }
        return SaResult.ok();
    }

    @GetMapping("/remove/{id}")
    @ResponseBody
    public SaResult deleteProduct(@PathVariable Integer id) {
        productService.removeById(id);
        return SaResult.ok();
    }

    @GetMapping("/{id}")
    public String getProductById(@PathVariable Integer id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("p", product);
        return "product_detail";
    }

    @GetMapping("/edit/{id}")
    public String editProduct(@PathVariable Integer id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("product", product);
        return "admin/product_edit";
    }

    @GetMapping
    public String getProduct(Model model,@RequestParam(required = false) String keyword) {
        List<Product> products;
        if (keyword==null||keyword.isEmpty()) {
            products = productService.list();
        } else {
            products = productService.list(new QueryWrapper<Product>()
                    .like("name", keyword));
        }
        model.addAttribute("products", products);
        return "admin/products";
    }

}
